<template>
  <div class="app-container">
    <time-select
      style="margin-top: 20px"
      ref="timeSelect"
      @selectYear="getList()"
      @selectSemester="getList()"
    ></time-select>
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="85px"
    >
      <el-form-item label="实验室名称" prop="labName">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入实验室名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实验室位置" prop="location">
        <el-input
          v-model="queryParams.location"
          placeholder="请输入实验室位置"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="实验室条件" prop="requirement">
        <el-input
          v-model="queryParams.requirement"
          placeholder="请输入实验室条件"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="实验室状态"
          clearable
          size="small"
        >
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="容纳人数" prop="number">
        <el-input
          v-model="queryParams.capacity"
          placeholder="请输入容纳人数"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          :disabled="labList.length == 0"
          >导出所有</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="labList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="实验室名称"
        align="center"
        prop="labName"
        show-overflow-tooltip
      />
      <el-table-column
        label="实验室位置"
        align="center"
        prop="location"
        show-overflow-tooltip
      />
      <el-table-column label="容纳人数" align="center" prop="capacity" />
      <el-table-column
        label="实验条件条件"
        align="center"
        prop="requirement"
        show-overflow-tooltip
      />
      <el-table-column
        label="所属学院"
        align="center"
        prop="deptName"
        show-overflow-tooltip
      />

      <el-table-column label="状态" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column
        label="实验室备注"
        align="center"
        prop="remarks"
        show-overflow-tooltip
      />
      <el-table-column
        label="创建时间"
        align="center"
        prop="gmtCreate"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.gmtCreate, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="更新时间"
        align="center"
        prop="gmtModified"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.gmtModified, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleRecord(scope.row)"
            >使用情况</el-button
          >
          <br />
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改实验室信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="实验室名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入实验室名称" />
        </el-form-item>
        <el-form-item label="实验室位置" prop="location">
          <el-input v-model="form.location" placeholder="请输入实验室位置" />
        </el-form-item>
        <el-form-item label="容纳人数" prop="capacity">
          <el-input-number v-model="form.capacity" :min="0" />
        </el-form-item>
        <el-form-item label="实验室条件" prop="requirement">
          <el-input v-model="form.requirement" placeholder="请输入实验室条件" />
        </el-form-item>
        <el-form-item label="所属学院" prop="deptId">
          <el-select
            style="width: 360px"
            v-model="form.deptId"
            placeholder="请选择"
            @change="handleDept()"
          >
            <el-option
              v-for="item in deptList"
              :key="item.deptId"
              :label="item.deptName"
              :value="item.deptId"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="实验室状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="实验室备注" prop="remarks">
          <el-input
            v-model="form.remarks"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="实验室简介">
          <editor v-model="form.brief" :min-height="192"/>
        </el-form-item>
        <el-form-item label="上传文件">
          <fileUpload v-model="form.filePath"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看实验室已预约时间段对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="timetableOpen"
      append-to-body
      width="85%"
    >
      <tb-course
        ref="tbCourse"
        table-label="查看已预约时间段"
        label="选择相应的位置确认时间段"
        @closeDialog="timetableOpen = false"
      ></tb-course>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  labList,
  getLab,
  delLab,
  addLab,
  updateLab,
  labExport,
  changeUserStatus,
  getMyDept,
} from "@/api/labbooking/lab";

import { mapGetters } from "vuex";
import tbCourse from "@/views/components/tbCourseDialog";
import timeSelect from "@/views/components/timeSelect";
import FileUpload from '@/components/FileUpload';
import {getToken} from "@/utils/auth";
import Editor from '@/components/Editor';

export default {
  name: "Lab",
  components: { timeSelect, tbCourse ,FileUpload , Editor,},
  computed: {
    ...mapGetters(["nickName", "phoneNumber"]),
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      userId: null,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 实验室信息表格数据
      labList: [],
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      timetableOpen: false,
      // 菜单状态数据字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      deptList: [
        // {
        //   deptId: 200,
        //   parentId: 0,
        //   deptName: "惠州学院",
        // },
        // {
        //   deptId: 201,
        //   parentId: 200,
        //   deptName: "计算机科学与工程学院",
        // },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "实验室名称不能为空", trigger: "blur" },
        ],
        location: [
          { required: true, message: "实验室位置不能为空", trigger: "blur" },
        ],
        capacity: [
          { required: true, message: "容纳人数不能为空", trigger: "blur" },
        ],
        status: [{ required: true, message: "状态不能为空", trigger: "blur" }],
        deptId: [{ required: true, message: "学院不能为空", trigger: "blur" }],
      },
      visible: false,
    };
  },
  created() {
    this.getList();
    this.getDicts("lms_lab_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDeptList();
  },
  methods: {
    /** 查询实验室信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      this.$nextTick(() => {
        this.queryParams.year = this.$refs.timeSelect.year;
        this.queryParams.term = this.$refs.timeSelect.semester;
        labList(this.queryParams).then((response) => {
          this.labList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      });
    },
    // 得到学院列表
    getDeptList() {
      getMyDept().then((res) => {
        this.deptList = res.data;
      });
    },
    // 专业状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 实验室预约状态修改
    handleStatusChange(row) {
      let text = row.status === 1 ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.userName + '"实验室吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeUserStatus(row.id, row.status);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.status = row.status === 0 ? 1 : 0;
        });
    },
    // 选学院后触发
    handleDept() {
      for (var i = 0; i < this.courseList.length; i++) {
        if (this.form.courseId == this.courseList[i].courseId) {
          this.form.className = this.courseList[i].className;
          this.form.number = this.courseList[i].number;
        }
      }
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.timetableOpen = false;
      this.reset();
    },
    // 查询实验室已预约记录
    handleRecord(row) {
      this.timetableOpen = true;
      this.title =
        "实验室名称：" + row.labName + "  实验室位置：" + row.location;

      this.$nextTick(() => {
        //解决this.$refs获取为undefined问题，等页面渲染完后再给子组件赋值
        this.$refs.tbCourse.labId = row.id;
        let year = this.$refs.timeSelect.year;
        let term = this.$refs.timeSelect.semester;
        this.$refs.tbCourse.year = year;
        this.$refs.tbCourse.term = term;
        this.$refs.tbCourse.getCourseTableData(row.id, year, term);
      });
    },

    // 表单重置
    reset() {
      this.form = {
        deptId:
          this.deptList.length > 1
            ? this.deptList[1].deptId
            : this.deptList[0].deptId,
        status: 1,
        capacity: 0,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams = {};
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.year = this.$refs.timeSelect.year;
      this.form.term = this.$refs.timeSelect.semester;
      this.form.userId = this.userId;
      this.open = true;
      this.title = "添加实验室信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.form.year = this.$refs.timeSelect.year;
      this.form.term = this.$refs.timeSelect.semester;
      const id = row.id || this.ids;
      getLab(id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改实验室信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateLab(this.form).then((response) => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addLab(this.form).then((response) => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm(
        '是否确认删除实验室信息编号为"' + ids + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delLab(ids);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有课程信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return labExport(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
  },
};
</script>

<style scoped>
.disvision >>> .el-input__inner {
  border: 0;
}
/* 如果你的 el-input type 设置成textarea ，就要用这个了 */
.disvision >>> .el-textarea__inner {
  border: 0;
  resize: none; /* 这个是去掉 textarea 下面拉伸的那个标志，如下图 */
}
</style>